package com.api.interfaces.jz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Path("/leaderview")
public class LeaderView {

    @POST
    @Path("/getleaderdata")
    @Produces(MediaType.TEXT_PLAIN)
    public String getleaderdata(@Context HttpServletRequest request, @Context HttpServletResponse response) throws ParseException {
        List<Map> meetingRoomList = new ArrayList<>();
        List<String> leaderList = null;
        List<LeaderUser> noSortList = new ArrayList();
        int day = 0;
        User user = HrmUserVarify.getUser(request, response);
        String userid = user.getUID() + "";
        // 打印用户 ID 信息
        new BaseBean().writeLog("当前用户 ID: " + userid);
        String nowyearmonth = TimeUtil.getCurrentDateString().substring(0, 7);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String yearmonth = Util.null2String(request.getParameter("yearmonth"));
        String lastname = Util.null2String(request.getParameter("lastname"));   // 新增：姓名
        RecordSet rs = new RecordSet();
//        String roleid = rs.getPropValue("leaderroleid", "roleid");
        String roleid = "";
        String cjroleid = rs.getPropValue("leaderroleid", "cjroleid");
        String zcjroleid = rs.getPropValue("leaderroleid", "zcjroleid");
        String queryzcjroleid = rs.getPropValue("leaderroleid", "queryzcjroleid");
        // 判断当前用户角色是否为queryzcjroleid
        RecordSet queryzcjRs = new RecordSet();
        String queryzcjRsSql = "select resourceid from HrmRoleMembers where roleid =? ";
        queryzcjRs.executeQuery(queryzcjRsSql, queryzcjroleid);
        while (queryzcjRs.next()) {
            String resourceid = Util.null2String(queryzcjRs.getString("resourceid"));
            if (userid.equals(resourceid)) {
                roleid = zcjroleid;
            } else {
                roleid = cjroleid;
            }
        }
        String role_sql = "select a.resourceid,b.dsporder from HrmRoleMembers a join hrmresource b on a.resourceid=b.id where roleid =? ";
        if (!"".equals(lastname)) {
            role_sql += " and b.lastname like '%" + lastname + "%' "; // 检索姓名
        }
        rs.executeQuery(role_sql, roleid);
        while (rs.next()) {
            noSortList.add(new LeaderUser(Util.null2String(rs.getString("resourceid")), Util.getDoubleValue(rs.getString("dsporder"))));
        }
        if (yearmonth.equals("")) {
            String nowday = TimeUtil.getCurrentDateString();
            day = getDaysOfMonth(sdf.parse(nowday));
            yearmonth = TimeUtil.getCurrentDateString().substring(0, 7);
        } else {
            day = getDaysOfMonth(sdf.parse(yearmonth + "-01"));
            nowyearmonth = yearmonth;
        }
        //排序
        leaderList = noSortList.stream()
                .sorted(Comparator.comparing(LeaderUser::getOrder).reversed())
                .map(LeaderUser::getXm)
                .collect(Collectors.toList());
        //创建线程池
        int numThreads = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
        List<Future<JSONObject>> futureList = new ArrayList<>();
        //拼接结果
//        String sql = "select cjrqx,cjsj,fjrqx,fjsj,mdd,cjsy,bm,wclx from uf_wcgljmbd where xm = ? and (substr(cjrqx,0,7)<=? or substr(fjrqx,0,7)>=?)";
        String sql = "select cjrqx,cjsj,fjrqx,fjsj,mdd,cjsy,bm,wclx from uf_wcgljmbd where xm = ? and (substring(cjrqx,0,7)<=? or substring(fjrqx,0,7)>=?)";
        for (String leader : leaderList) {
            String finalYearmonth = yearmonth;
            String finalYearmonth1 = yearmonth;
            int finalDay = day;
            String finalNowyearmonth = nowyearmonth;
            RecordSet rst = new RecordSet();
            RecordSet finalRst = rst;
            Future<JSONObject> future = executorService.submit(() -> {
                JSONObject object = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < finalDay * 2; i++) {
                    JSONObject jsonObject = new JSONObject();
                    finalRst.executeQuery(sql, leader, finalYearmonth, finalYearmonth1);
                    while (finalRst.next()) {
                        String starttime = Util.null2String(finalRst.getString("cjrqx")) + " " + Util.null2String(finalRst.getString("cjsj"));
                        String endtime = Util.null2String(finalRst.getString("fjrqx")) + " " + Util.null2String(finalRst.getString("fjsj"));
                        String mdd = Util.null2String(finalRst.getString("mdd"));
                        String cjsy = Util.null2String(finalRst.getString("cjsy"));
                        String bm = Util.null2String(finalRst.getString("bm"));
                        String wclx = Util.null2String(finalRst.getString("wclx"));
                        String everystartime = "";
                        String everyendtime = "";
                        if (i % 2 != 0) {
                            int everyday = (i + 1) / 2;
                            everystartime = finalNowyearmonth + "-" + everyday + " 12:00";
                            everyendtime = finalNowyearmonth + "-" + everyday + " 24:00";
                        } else {
                            int everyday;
                            if (i == 0) {
                                everyday = 1;
                            } else {
                                everyday = i / 2 + 1;
                            }
                            everystartime = finalNowyearmonth + "-" + everyday + " 00:00";
                            everyendtime = finalNowyearmonth + "-" + everyday + " 12:00";

                        }
                        boolean b = isOverlap(starttime, endtime, everystartime, everyendtime);
                        if (b) {
                            jsonObject.put(i + "", mdd);
                            jsonObject.put(i + 100000 + "", getDepartmentname(bm));
                            jsonObject.put(i + 200000 + "", cjsy);
                            jsonObject.put(i + 300000 + "", wclx);
                        }

                    }
                    jsonArray.add(jsonObject);
                }
                object.put(getlastname(leader) + "_" + leader, jsonArray);
                return object;
            });
            rst = null;
            futureList.add(future);
        }
        executorService.shutdown();
        JSONArray array = new JSONArray();
        for (Future<JSONObject> future : futureList) {
            try {
                array.add(future.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSONObject.toJSONString(array);
    }


    @POST
    @Path("/savedata")
    @Produces(MediaType.TEXT_PLAIN)
    public void savedata(@Context HttpServletRequest request, @Context HttpServletResponse response) throws
            ParseException {
        Map<String, Object> params = ParamUtil.request2Map(request);
        RecordSet rs = new RecordSet();
        String formid = getModeidByTablename(rs, "uf_wcgljmbd");
        new BaseBean().writeLog("=====params:" + params);
        String yearmonth = params.get("yearmonth").toString();
        if (yearmonth.equals("")) {
            yearmonth = TimeUtil.getCurrentDateString().substring(0, 7);
        }
        for (String key : params.keySet()) {
            String id = key.split("_")[0];
            if (id.matches("[0-9]+")) {
                String cjrq = yearmonth;
                String fjrq = yearmonth;
                String cjsj = "";
                String fjsj = "";
                int day = Integer.parseInt(key.split("_")[1]);
                if (day % 2 != 0) {
                    int nowday = (day + 1) / 2;
                    if (nowday < 10) {
                        cjrq = cjrq + "-0" + nowday;
                        fjrq = fjrq + "-0" + nowday;
                    } else {
                        cjrq = cjrq + "-" + nowday;
                        fjrq = fjrq + "-" + nowday;
                    }
                    cjsj = "08:30";
                    fjsj = "12:00";
                } else {
                    int nowday = day / 2;
                    if (nowday < 10) {
                        cjrq = cjrq + "-0" + nowday;
                        fjrq = fjrq + "-0" + nowday;
                    } else {
                        cjrq = cjrq + "-" + nowday;
                        fjrq = fjrq + "-" + nowday;
                    }
                    cjsj = "12:00";
                    fjsj = "18:00";
                }
                String value = params.get(key).toString();
                User user = new User(Integer.parseInt(id));
                String uuid = UUID.randomUUID().toString();
                String sql = "insert into uf_wcgljmbd(bm,xm,mdd,cjrqx,fjrqx,cjsj,fjsj,formmodeid,modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,modedatacreatertype) values(?,?,?,?,?,?,?,?,'" + uuid + "',1,'" + TimeUtil.getCurrentDateString() + "','" + TimeUtil.getOnlyCurrentTimeString() + "','0')";

                boolean b = rs.executeUpdate(sql, user.getUserDepartment(), id, value, cjrq, fjrq, cjsj, fjsj, formid);
                new BaseBean().writeLog("========b:" + b);
                new BaseBean().writeLog("========sql:" + sql);
                if (b) {
                    rs.execute("select id from uf_wcgljmbd where modeuuid='" + uuid + "'");
                    rs.next();
                    int dataId = Util.getIntValue(rs.getString("id"));
                    if (dataId > 0) {
                        //权限重构
                        ModeRightInfo ModeRightInfo = new ModeRightInfo();
                        ModeRightInfo.setNewRight(true);
                        ModeRightInfo.editModeDataShare(1, Integer.parseInt(formid), dataId);
                    }
                }
            }

        }

    }

    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    public static boolean isOverlap(String starttime, String endtime, String everystartime, String everyendtime) throws
            ParseException {
        //造3个时间段数据
        List<Timestamp> periodStart = new ArrayList<Timestamp>();
        List<Timestamp> periodend = new ArrayList<Timestamp>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //第一个时间段
        Date start1 = sdf.parse(starttime);
        Date end1 = sdf.parse(endtime);
        //第二个时间段
        Date start2 = sdf.parse(everystartime);
        Date end2 = sdf.parse(everyendtime);

        //开始时间放到一个数组
        periodStart.add(new Timestamp(start1.getTime()));
        periodStart.add(new Timestamp(start2.getTime()));

        //结束时间放到一个数组
        periodend.add(new Timestamp(end1.getTime()));
        periodend.add(new Timestamp(end2.getTime()));

        /**
         * 两两循环比较
         * 这里的3代表有三组数据，先写死
         */
        for (int i = 0; i < periodStart.size() - 1; i++) {
            Timestamp start0 = periodStart.get(i);
            Timestamp end0 = periodend.get(i);
            for (int j = i + 1; j < periodStart.size(); j++) {
                Timestamp start = periodStart.get(j);
                Timestamp end = periodend.get(j);
                if (start0.compareTo(end) >= 0 || end0.compareTo(start) <= 0) {
                    /**
                     * 说明不重复。
                     * 思路：该时间段的开始时间如何大于另个一个时间段的结束时间，那么这个两个时间段不会有重叠；
                     * 如果该时间段的结束时间小于另一个时间段的时间，那么这个两个时间段也不会有重叠。
                     */
                    continue;
                } else {
                    //说明该时间段重复
                    return true;
                }
            }
        }

        return false;
    }


    public static String getlastname(String id) {
        RecordSet rs = new RecordSet();
        String lastname = "";
        String sql = "select lastname from hrmresource where id = ?";
        rs.executeQuery(sql, id);
        if (rs.next()) {
            lastname = Util.null2String(rs.getString("lastname"));
        }
        return lastname;
    }

    public static String getDepartmentname(String id) {
        RecordSet rs = new RecordSet();
        String departmentname = "";
        String sql = "select departmentname from hrmdepartment where id = ?";
        rs.executeQuery(sql, id);
        if (rs.next()) {
            departmentname = Util.null2String(rs.getString("departmentname"));
        }
        return departmentname;
    }

    /**
     * 通过建模表表名获取所属模块id
     *
     * @param rs
     * @param tablename
     * @return
     */
    public static String getModeidByTablename(RecordSet rs, String tablename) {
        String modeid = "0";
        rs.executeQuery("select id from modeinfo where formid=(select id from workflow_bill where tablename=?)",
                tablename);
        if (rs.next()) {
            modeid = Util.null2String(rs.getString("id"));
        }
        return modeid;
    }


}
